
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>3. Kaleidoscope: Code generation to LLVM IR &mdash; LLVM 3.7 documentation</title>
    
    <link rel="stylesheet" href="../_static/llvm-theme.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '3.7',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <link rel="top" title="LLVM 3.7 documentation" href="../index.html" />
    <link rel="up" title="LLVM Tutorial: Table of Contents" href="index.html" />
    <link rel="next" title="4. Kaleidoscope: Adding JIT and Optimizer Support" href="LangImpl4.html" />
    <link rel="prev" title="2. Kaleidoscope: Implementing a Parser and AST" href="LangImpl2.html" />
<style type="text/css">
  table.right { float: right; margin-left: 20px; }
  table.right td { border: 1px solid #ccc; }
</style>

  </head>
  <body role="document">
<div class="logo">
  <a href="../index.html">
    <img src="../_static/logo.png"
         alt="LLVM Logo" width="250" height="88"/></a>
</div>

    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="LangImpl4.html" title="4. Kaleidoscope: Adding JIT and Optimizer Support"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="LangImpl2.html" title="2. Kaleidoscope: Implementing a Parser and AST"
             accesskey="P">previous</a> |</li>
  <li><a href="http://llvm.org/">LLVM Home</a>&nbsp;|&nbsp;</li>
  <li><a href="../index.html">Documentation</a>&raquo;</li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">LLVM Tutorial: Table of Contents</a> &raquo;</li> 
      </ul>
    </div>


    <div class="document">
      <div class="documentwrapper">
          <div class="body" role="main">
            
  <div class="section" id="kaleidoscope-code-generation-to-llvm-ir">
<h1>3. Kaleidoscope: Code generation to LLVM IR<a class="headerlink" href="#kaleidoscope-code-generation-to-llvm-ir" title="Permalink to this headline">¶</a></h1>
<div class="contents local topic" id="contents">
<ul class="simple">
<li><a class="reference internal" href="#chapter-3-introduction" id="id1">Chapter 3 Introduction</a></li>
<li><a class="reference internal" href="#code-generation-setup" id="id2">Code Generation Setup</a></li>
<li><a class="reference internal" href="#expression-code-generation" id="id3">Expression Code Generation</a></li>
<li><a class="reference internal" href="#function-code-generation" id="id4">Function Code Generation</a></li>
<li><a class="reference internal" href="#driver-changes-and-closing-thoughts" id="id5">Driver Changes and Closing Thoughts</a></li>
<li><a class="reference internal" href="#full-code-listing" id="id6">Full Code Listing</a></li>
</ul>
</div>
<div class="section" id="chapter-3-introduction">
<h2><a class="toc-backref" href="#id1">3.1. Chapter 3 Introduction</a><a class="headerlink" href="#chapter-3-introduction" title="Permalink to this headline">¶</a></h2>
<p>Welcome to Chapter 3 of the &#8220;<a class="reference external" href="index.html">Implementing a language with
LLVM</a>&#8221; tutorial. This chapter shows you how to transform
the <a class="reference external" href="LangImpl2.html">Abstract Syntax Tree</a>, built in Chapter 2, into
LLVM IR. This will teach you a little bit about how LLVM does things, as
well as demonstrate how easy it is to use. It&#8217;s much more work to build
a lexer and parser than it is to generate LLVM IR code. :)</p>
<p><strong>Please note</strong>: the code in this chapter and later require LLVM 2.2 or
later. LLVM 2.1 and before will not work with it. Also note that you
need to use a version of this tutorial that matches your LLVM release:
If you are using an official LLVM release, use the version of the
documentation included with your release or on the <a class="reference external" href="http://llvm.org/releases/">llvm.org releases
page</a>.</p>
</div>
<div class="section" id="code-generation-setup">
<h2><a class="toc-backref" href="#id2">3.2. Code Generation Setup</a><a class="headerlink" href="#code-generation-setup" title="Permalink to this headline">¶</a></h2>
<p>In order to generate LLVM IR, we want some simple setup to get started.
First we define virtual code generation (codegen) methods in each AST
class:</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="c1">/// ExprAST - Base class for all expression nodes.</span>
<span class="k">class</span> <span class="nc">ExprAST</span> <span class="p">{</span>
<span class="k">public</span><span class="o">:</span>
  <span class="k">virtual</span> <span class="o">~</span><span class="n">ExprAST</span><span class="p">()</span> <span class="p">{}</span>
  <span class="k">virtual</span> <span class="n">Value</span> <span class="o">*</span><span class="n">Codegen</span><span class="p">()</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">};</span>

<span class="c1">/// NumberExprAST - Expression class for numeric literals like &quot;1.0&quot;.</span>
<span class="k">class</span> <span class="nc">NumberExprAST</span> <span class="o">:</span> <span class="k">public</span> <span class="n">ExprAST</span> <span class="p">{</span>
  <span class="kt">double</span> <span class="n">Val</span><span class="p">;</span>
<span class="k">public</span><span class="o">:</span>
  <span class="n">NumberExprAST</span><span class="p">(</span><span class="kt">double</span> <span class="n">val</span><span class="p">)</span> <span class="o">:</span> <span class="n">Val</span><span class="p">(</span><span class="n">val</span><span class="p">)</span> <span class="p">{}</span>
  <span class="k">virtual</span> <span class="n">Value</span> <span class="o">*</span><span class="n">Codegen</span><span class="p">();</span>
<span class="p">};</span>
<span class="p">...</span>
</pre></div>
</div>
<p>The Codegen() method says to emit IR for that AST node along with all
the things it depends on, and they all return an LLVM Value object.
&#8220;Value&#8221; is the class used to represent a &#8220;<a class="reference external" href="http://en.wikipedia.org/wiki/Static_single_assignment_form">Static Single Assignment
(SSA)</a>
register&#8221; or &#8220;SSA value&#8221; in LLVM. The most distinct aspect of SSA values
is that their value is computed as the related instruction executes, and
it does not get a new value until (and if) the instruction re-executes.
In other words, there is no way to &#8220;change&#8221; an SSA value. For more
information, please read up on <a class="reference external" href="http://en.wikipedia.org/wiki/Static_single_assignment_form">Static Single
Assignment</a>
- the concepts are really quite natural once you grok them.</p>
<p>Note that instead of adding virtual methods to the ExprAST class
hierarchy, it could also make sense to use a <a class="reference external" href="http://en.wikipedia.org/wiki/Visitor_pattern">visitor
pattern</a> or some other
way to model this. Again, this tutorial won&#8217;t dwell on good software
engineering practices: for our purposes, adding a virtual method is
simplest.</p>
<p>The second thing we want is an &#8220;Error&#8221; method like we used for the
parser, which will be used to report errors found during code generation
(for example, use of an undeclared parameter):</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="n">Value</span> <span class="o">*</span><span class="nf">ErrorV</span><span class="p">(</span><span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">Str</span><span class="p">)</span> <span class="p">{</span> <span class="n">Error</span><span class="p">(</span><span class="n">Str</span><span class="p">);</span> <span class="k">return</span> <span class="mi">0</span><span class="p">;</span> <span class="p">}</span>

<span class="k">static</span> <span class="n">Module</span> <span class="o">*</span><span class="n">TheModule</span><span class="p">;</span>
<span class="k">static</span> <span class="n">IRBuilder</span><span class="o">&lt;&gt;</span> <span class="n">Builder</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">());</span>
<span class="k">static</span> <span class="n">std</span><span class="o">::</span><span class="n">map</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="p">,</span> <span class="n">Value</span><span class="o">*&gt;</span> <span class="n">NamedValues</span><span class="p">;</span>
</pre></div>
</div>
<p>The static variables will be used during code generation. <code class="docutils literal"><span class="pre">TheModule</span></code>
is the LLVM construct that contains all of the functions and global
variables in a chunk of code. In many ways, it is the top-level
structure that the LLVM IR uses to contain code.</p>
<p>The <code class="docutils literal"><span class="pre">Builder</span></code> object is a helper object that makes it easy to generate
LLVM instructions. Instances of the
<a class="reference external" href="http://llvm.org/doxygen/IRBuilder_8h-source.html">IRBuilder</a>
class template keep track of the current place to insert instructions
and has methods to create new instructions.</p>
<p>The <code class="docutils literal"><span class="pre">NamedValues</span></code> map keeps track of which values are defined in the
current scope and what their LLVM representation is. (In other words, it
is a symbol table for the code). In this form of Kaleidoscope, the only
things that can be referenced are function parameters. As such, function
parameters will be in this map when generating code for their function
body.</p>
<p>With these basics in place, we can start talking about how to generate
code for each expression. Note that this assumes that the <code class="docutils literal"><span class="pre">Builder</span></code>
has been set up to generate code <em>into</em> something. For now, we&#8217;ll assume
that this has already been done, and we&#8217;ll just use it to emit code.</p>
</div>
<div class="section" id="expression-code-generation">
<h2><a class="toc-backref" href="#id3">3.3. Expression Code Generation</a><a class="headerlink" href="#expression-code-generation" title="Permalink to this headline">¶</a></h2>
<p>Generating LLVM code for expression nodes is very straightforward: less
than 45 lines of commented code for all four of our expression nodes.
First we&#8217;ll do numeric literals:</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="n">Value</span> <span class="o">*</span><span class="n">NumberExprAST</span><span class="o">::</span><span class="n">Codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">return</span> <span class="n">ConstantFP</span><span class="o">::</span><span class="n">get</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">(),</span> <span class="n">APFloat</span><span class="p">(</span><span class="n">Val</span><span class="p">));</span>
<span class="p">}</span>
</pre></div>
</div>
<p>In the LLVM IR, numeric constants are represented with the
<code class="docutils literal"><span class="pre">ConstantFP</span></code> class, which holds the numeric value in an <code class="docutils literal"><span class="pre">APFloat</span></code>
internally (<code class="docutils literal"><span class="pre">APFloat</span></code> has the capability of holding floating point
constants of Arbitrary Precision). This code basically just creates
and returns a <code class="docutils literal"><span class="pre">ConstantFP</span></code>. Note that in the LLVM IR that constants
are all uniqued together and shared. For this reason, the API uses the
&#8220;foo::get(...)&#8221; idiom instead of &#8220;new foo(..)&#8221; or &#8220;foo::Create(..)&#8221;.</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="n">Value</span> <span class="o">*</span><span class="n">VariableExprAST</span><span class="o">::</span><span class="n">Codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="c1">// Look this variable up in the function.</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">V</span> <span class="o">=</span> <span class="n">NamedValues</span><span class="p">[</span><span class="n">Name</span><span class="p">];</span>
  <span class="k">return</span> <span class="n">V</span> <span class="o">?</span> <span class="nl">V</span> <span class="p">:</span> <span class="n">ErrorV</span><span class="p">(</span><span class="s">&quot;Unknown variable name&quot;</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>References to variables are also quite simple using LLVM. In the simple
version of Kaleidoscope, we assume that the variable has already been
emitted somewhere and its value is available. In practice, the only
values that can be in the <code class="docutils literal"><span class="pre">NamedValues</span></code> map are function arguments.
This code simply checks to see that the specified name is in the map (if
not, an unknown variable is being referenced) and returns the value for
it. In future chapters, we&#8217;ll add support for <a class="reference external" href="LangImpl5.html#for">loop induction
variables</a> in the symbol table, and for <a class="reference external" href="LangImpl7.html#localvars">local
variables</a>.</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="n">Value</span> <span class="o">*</span><span class="n">BinaryExprAST</span><span class="o">::</span><span class="n">Codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">L</span> <span class="o">=</span> <span class="n">LHS</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">();</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">R</span> <span class="o">=</span> <span class="n">RHS</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">L</span> <span class="o">==</span> <span class="mi">0</span> <span class="o">||</span> <span class="n">R</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span> <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>

  <span class="k">switch</span> <span class="p">(</span><span class="n">Op</span><span class="p">)</span> <span class="p">{</span>
  <span class="k">case</span> <span class="sc">&#39;+&#39;</span><span class="o">:</span> <span class="k">return</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateFAdd</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">R</span><span class="p">,</span> <span class="s">&quot;addtmp&quot;</span><span class="p">);</span>
  <span class="k">case</span> <span class="sc">&#39;-&#39;</span><span class="o">:</span> <span class="k">return</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateFSub</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">R</span><span class="p">,</span> <span class="s">&quot;subtmp&quot;</span><span class="p">);</span>
  <span class="k">case</span> <span class="sc">&#39;*&#39;</span><span class="o">:</span> <span class="k">return</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateFMul</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">R</span><span class="p">,</span> <span class="s">&quot;multmp&quot;</span><span class="p">);</span>
  <span class="k">case</span> <span class="sc">&#39;&lt;&#39;</span><span class="o">:</span>
    <span class="n">L</span> <span class="o">=</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateFCmpULT</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">R</span><span class="p">,</span> <span class="s">&quot;cmptmp&quot;</span><span class="p">);</span>
    <span class="c1">// Convert bool 0/1 to double 0.0 or 1.0</span>
    <span class="k">return</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateUIToFP</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">Type</span><span class="o">::</span><span class="n">getDoubleTy</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">()),</span>
                                <span class="s">&quot;booltmp&quot;</span><span class="p">);</span>
  <span class="k">default</span><span class="o">:</span> <span class="k">return</span> <span class="n">ErrorV</span><span class="p">(</span><span class="s">&quot;invalid binary operator&quot;</span><span class="p">);</span>
  <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Binary operators start to get more interesting. The basic idea here is
that we recursively emit code for the left-hand side of the expression,
then the right-hand side, then we compute the result of the binary
expression. In this code, we do a simple switch on the opcode to create
the right LLVM instruction.</p>
<p>In the example above, the LLVM builder class is starting to show its
value. IRBuilder knows where to insert the newly created instruction,
all you have to do is specify what instruction to create (e.g. with
<code class="docutils literal"><span class="pre">CreateFAdd</span></code>), which operands to use (<code class="docutils literal"><span class="pre">L</span></code> and <code class="docutils literal"><span class="pre">R</span></code> here) and
optionally provide a name for the generated instruction.</p>
<p>One nice thing about LLVM is that the name is just a hint. For instance,
if the code above emits multiple &#8220;addtmp&#8221; variables, LLVM will
automatically provide each one with an increasing, unique numeric
suffix. Local value names for instructions are purely optional, but it
makes it much easier to read the IR dumps.</p>
<p><a class="reference external" href="../LangRef.html#instref">LLVM instructions</a> are constrained by strict
rules: for example, the Left and Right operators of an <a class="reference external" href="../LangRef.html#i_add">add
instruction</a> must have the same type, and the
result type of the add must match the operand types. Because all values
in Kaleidoscope are doubles, this makes for very simple code for add,
sub and mul.</p>
<p>On the other hand, LLVM specifies that the <a class="reference external" href="../LangRef.html#i_fcmp">fcmp
instruction</a> always returns an &#8216;i1&#8217; value (a
one bit integer). The problem with this is that Kaleidoscope wants the
value to be a 0.0 or 1.0 value. In order to get these semantics, we
combine the fcmp instruction with a <a class="reference external" href="../LangRef.html#i_uitofp">uitofp
instruction</a>. This instruction converts its
input integer into a floating point value by treating the input as an
unsigned value. In contrast, if we used the <a class="reference external" href="../LangRef.html#i_sitofp">sitofp
instruction</a>, the Kaleidoscope &#8216;&lt;&#8217; operator
would return 0.0 and -1.0, depending on the input value.</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="n">Value</span> <span class="o">*</span><span class="n">CallExprAST</span><span class="o">::</span><span class="n">Codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="c1">// Look up the name in the global module table.</span>
  <span class="n">Function</span> <span class="o">*</span><span class="n">CalleeF</span> <span class="o">=</span> <span class="n">TheModule</span><span class="o">-&gt;</span><span class="n">getFunction</span><span class="p">(</span><span class="n">Callee</span><span class="p">);</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">CalleeF</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">ErrorV</span><span class="p">(</span><span class="s">&quot;Unknown function referenced&quot;</span><span class="p">);</span>

  <span class="c1">// If argument mismatch error.</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">CalleeF</span><span class="o">-&gt;</span><span class="n">arg_size</span><span class="p">()</span> <span class="o">!=</span> <span class="n">Args</span><span class="p">.</span><span class="n">size</span><span class="p">())</span>
    <span class="k">return</span> <span class="n">ErrorV</span><span class="p">(</span><span class="s">&quot;Incorrect # arguments passed&quot;</span><span class="p">);</span>

  <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">Value</span><span class="o">*&gt;</span> <span class="n">ArgsV</span><span class="p">;</span>
  <span class="k">for</span> <span class="p">(</span><span class="kt">unsigned</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="n">e</span> <span class="o">=</span> <span class="n">Args</span><span class="p">.</span><span class="n">size</span><span class="p">();</span> <span class="n">i</span> <span class="o">!=</span> <span class="n">e</span><span class="p">;</span> <span class="o">++</span><span class="n">i</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">ArgsV</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="n">Args</span><span class="p">[</span><span class="n">i</span><span class="p">]</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">());</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">ArgsV</span><span class="p">.</span><span class="n">back</span><span class="p">()</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span> <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="k">return</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateCall</span><span class="p">(</span><span class="n">CalleeF</span><span class="p">,</span> <span class="n">ArgsV</span><span class="p">,</span> <span class="s">&quot;calltmp&quot;</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Code generation for function calls is quite straightforward with LLVM.
The code above initially does a function name lookup in the LLVM
Module&#8217;s symbol table. Recall that the LLVM Module is the container that
holds all of the functions we are JIT&#8217;ing. By giving each function the
same name as what the user specifies, we can use the LLVM symbol table
to resolve function names for us.</p>
<p>Once we have the function to call, we recursively codegen each argument
that is to be passed in, and create an LLVM <a class="reference external" href="../LangRef.html#i_call">call
instruction</a>. Note that LLVM uses the native C
calling conventions by default, allowing these calls to also call into
standard library functions like &#8220;sin&#8221; and &#8220;cos&#8221;, with no additional
effort.</p>
<p>This wraps up our handling of the four basic expressions that we have so
far in Kaleidoscope. Feel free to go in and add some more. For example,
by browsing the <a class="reference external" href="../LangRef.html">LLVM language reference</a> you&#8217;ll find
several other interesting instructions that are really easy to plug into
our basic framework.</p>
</div>
<div class="section" id="function-code-generation">
<h2><a class="toc-backref" href="#id4">3.4. Function Code Generation</a><a class="headerlink" href="#function-code-generation" title="Permalink to this headline">¶</a></h2>
<p>Code generation for prototypes and functions must handle a number of
details, which make their code less beautiful than expression code
generation, but allows us to illustrate some important points. First,
lets talk about code generation for prototypes: they are used both for
function bodies and external function declarations. The code starts
with:</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="n">Function</span> <span class="o">*</span><span class="n">PrototypeAST</span><span class="o">::</span><span class="n">Codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="c1">// Make the function type:  double(double,double) etc.</span>
  <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">Type</span><span class="o">*&gt;</span> <span class="n">Doubles</span><span class="p">(</span><span class="n">Args</span><span class="p">.</span><span class="n">size</span><span class="p">(),</span>
                             <span class="n">Type</span><span class="o">::</span><span class="n">getDoubleTy</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">()));</span>
  <span class="n">FunctionType</span> <span class="o">*</span><span class="n">FT</span> <span class="o">=</span> <span class="n">FunctionType</span><span class="o">::</span><span class="n">get</span><span class="p">(</span><span class="n">Type</span><span class="o">::</span><span class="n">getDoubleTy</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">()),</span>
                                       <span class="n">Doubles</span><span class="p">,</span> <span class="nb">false</span><span class="p">);</span>

  <span class="n">Function</span> <span class="o">*</span><span class="n">F</span> <span class="o">=</span> <span class="n">Function</span><span class="o">::</span><span class="n">Create</span><span class="p">(</span><span class="n">FT</span><span class="p">,</span> <span class="n">Function</span><span class="o">::</span><span class="n">ExternalLinkage</span><span class="p">,</span> <span class="n">Name</span><span class="p">,</span> <span class="n">TheModule</span><span class="p">);</span>
</pre></div>
</div>
<p>This code packs a lot of power into a few lines. Note first that this
function returns a &#8220;Function*&#8221; instead of a &#8220;Value*&#8221;. Because a
&#8220;prototype&#8221; really talks about the external interface for a function
(not the value computed by an expression), it makes sense for it to
return the LLVM Function it corresponds to when codegen&#8217;d.</p>
<p>The call to <code class="docutils literal"><span class="pre">FunctionType::get</span></code> creates the <code class="docutils literal"><span class="pre">FunctionType</span></code> that
should be used for a given Prototype. Since all function arguments in
Kaleidoscope are of type double, the first line creates a vector of &#8220;N&#8221;
LLVM double types. It then uses the <code class="docutils literal"><span class="pre">Functiontype::get</span></code> method to
create a function type that takes &#8220;N&#8221; doubles as arguments, returns one
double as a result, and that is not vararg (the false parameter
indicates this). Note that Types in LLVM are uniqued just like Constants
are, so you don&#8217;t &#8220;new&#8221; a type, you &#8220;get&#8221; it.</p>
<p>The final line above actually creates the function that the prototype
will correspond to. This indicates the type, linkage and name to use, as
well as which module to insert into. &#8220;<a class="reference external" href="../LangRef.html#linkage">external
linkage</a>&#8221; means that the function may be
defined outside the current module and/or that it is callable by
functions outside the module. The Name passed in is the name the user
specified: since &#8220;<code class="docutils literal"><span class="pre">TheModule</span></code>&#8221; is specified, this name is registered
in &#8220;<code class="docutils literal"><span class="pre">TheModule</span></code>&#8220;s symbol table, which is used by the function call
code above.</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="c1">// If F conflicted, there was already something named &#39;Name&#39;.  If it has a</span>
<span class="c1">// body, don&#39;t allow redefinition or reextern.</span>
<span class="k">if</span> <span class="p">(</span><span class="n">F</span><span class="o">-&gt;</span><span class="n">getName</span><span class="p">()</span> <span class="o">!=</span> <span class="n">Name</span><span class="p">)</span> <span class="p">{</span>
  <span class="c1">// Delete the one we just made and get the existing one.</span>
  <span class="n">F</span><span class="o">-&gt;</span><span class="n">eraseFromParent</span><span class="p">();</span>
  <span class="n">F</span> <span class="o">=</span> <span class="n">TheModule</span><span class="o">-&gt;</span><span class="n">getFunction</span><span class="p">(</span><span class="n">Name</span><span class="p">);</span>
</pre></div>
</div>
<p>The Module symbol table works just like the Function symbol table when
it comes to name conflicts: if a new function is created with a name
that was previously added to the symbol table, the new function will get
implicitly renamed when added to the Module. The code above exploits
this fact to determine if there was a previous definition of this
function.</p>
<p>In Kaleidoscope, I choose to allow redefinitions of functions in two
cases: first, we want to allow &#8216;extern&#8217;ing a function more than once, as
long as the prototypes for the externs match (since all arguments have
the same type, we just have to check that the number of arguments
match). Second, we want to allow &#8216;extern&#8217;ing a function and then
defining a body for it. This is useful when defining mutually recursive
functions.</p>
<p>In order to implement this, the code above first checks to see if there
is a collision on the name of the function. If so, it deletes the
function we just created (by calling <code class="docutils literal"><span class="pre">eraseFromParent</span></code>) and then
calling <code class="docutils literal"><span class="pre">getFunction</span></code> to get the existing function with the specified
name. Note that many APIs in LLVM have &#8220;erase&#8221; forms and &#8220;remove&#8221; forms.
The &#8220;remove&#8221; form unlinks the object from its parent (e.g. a Function
from a Module) and returns it. The &#8220;erase&#8221; form unlinks the object and
then deletes it.</p>
<div class="highlight-c++"><div class="highlight"><pre>  <span class="c1">// If F already has a body, reject this.</span>
  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">F</span><span class="o">-&gt;</span><span class="n">empty</span><span class="p">())</span> <span class="p">{</span>
    <span class="n">ErrorF</span><span class="p">(</span><span class="s">&quot;redefinition of function&quot;</span><span class="p">);</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="c1">// If F took a different number of args, reject.</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">F</span><span class="o">-&gt;</span><span class="n">arg_size</span><span class="p">()</span> <span class="o">!=</span> <span class="n">Args</span><span class="p">.</span><span class="n">size</span><span class="p">())</span> <span class="p">{</span>
    <span class="n">ErrorF</span><span class="p">(</span><span class="s">&quot;redefinition of function with different # args&quot;</span><span class="p">);</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
  <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>In order to verify the logic above, we first check to see if the
pre-existing function is &#8220;empty&#8221;. In this case, empty means that it has
no basic blocks in it, which means it has no body. If it has no body, it
is a forward declaration. Since we don&#8217;t allow anything after a full
definition of the function, the code rejects this case. If the previous
reference to a function was an &#8216;extern&#8217;, we simply verify that the
number of arguments for that definition and this one match up. If not,
we emit an error.</p>
<div class="highlight-c++"><div class="highlight"><pre>  <span class="c1">// Set names for all arguments.</span>
  <span class="kt">unsigned</span> <span class="n">Idx</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
  <span class="k">for</span> <span class="p">(</span><span class="n">Function</span><span class="o">::</span><span class="n">arg_iterator</span> <span class="n">AI</span> <span class="o">=</span> <span class="n">F</span><span class="o">-&gt;</span><span class="n">arg_begin</span><span class="p">();</span> <span class="n">Idx</span> <span class="o">!=</span> <span class="n">Args</span><span class="p">.</span><span class="n">size</span><span class="p">();</span>
       <span class="o">++</span><span class="n">AI</span><span class="p">,</span> <span class="o">++</span><span class="n">Idx</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">AI</span><span class="o">-&gt;</span><span class="n">setName</span><span class="p">(</span><span class="n">Args</span><span class="p">[</span><span class="n">Idx</span><span class="p">]);</span>

    <span class="c1">// Add arguments to variable symbol table.</span>
    <span class="n">NamedValues</span><span class="p">[</span><span class="n">Args</span><span class="p">[</span><span class="n">Idx</span><span class="p">]]</span> <span class="o">=</span> <span class="n">AI</span><span class="p">;</span>
  <span class="p">}</span>
  <span class="k">return</span> <span class="n">F</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The last bit of code for prototypes loops over all of the arguments in
the function, setting the name of the LLVM Argument objects to match,
and registering the arguments in the <code class="docutils literal"><span class="pre">NamedValues</span></code> map for future use
by the <code class="docutils literal"><span class="pre">VariableExprAST</span></code> AST node. Once this is set up, it returns the
Function object to the caller. Note that we don&#8217;t check for conflicting
argument names here (e.g. &#8220;extern foo(a b a)&#8221;). Doing so would be very
straight-forward with the mechanics we have already used above.</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="n">Function</span> <span class="o">*</span><span class="n">FunctionAST</span><span class="o">::</span><span class="n">Codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">NamedValues</span><span class="p">.</span><span class="n">clear</span><span class="p">();</span>

  <span class="n">Function</span> <span class="o">*</span><span class="n">TheFunction</span> <span class="o">=</span> <span class="n">Proto</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">TheFunction</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
</pre></div>
</div>
<p>Code generation for function definitions starts out simply enough: we
just codegen the prototype (Proto) and verify that it is ok. We then
clear out the <code class="docutils literal"><span class="pre">NamedValues</span></code> map to make sure that there isn&#8217;t anything
in it from the last function we compiled. Code generation of the
prototype ensures that there is an LLVM Function object that is ready to
go for us.</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="c1">// Create a new basic block to start insertion into.</span>
<span class="n">BasicBlock</span> <span class="o">*</span><span class="n">BB</span> <span class="o">=</span> <span class="n">BasicBlock</span><span class="o">::</span><span class="n">Create</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">(),</span> <span class="s">&quot;entry&quot;</span><span class="p">,</span> <span class="n">TheFunction</span><span class="p">);</span>
<span class="n">Builder</span><span class="p">.</span><span class="n">SetInsertPoint</span><span class="p">(</span><span class="n">BB</span><span class="p">);</span>

<span class="k">if</span> <span class="p">(</span><span class="n">Value</span> <span class="o">*</span><span class="n">RetVal</span> <span class="o">=</span> <span class="n">Body</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">())</span> <span class="p">{</span>
</pre></div>
</div>
<p>Now we get to the point where the <code class="docutils literal"><span class="pre">Builder</span></code> is set up. The first line
creates a new <a class="reference external" href="http://en.wikipedia.org/wiki/Basic_block">basic block</a>
(named &#8220;entry&#8221;), which is inserted into <code class="docutils literal"><span class="pre">TheFunction</span></code>. The second line
then tells the builder that new instructions should be inserted into the
end of the new basic block. Basic blocks in LLVM are an important part
of functions that define the <a class="reference external" href="http://en.wikipedia.org/wiki/Control_flow_graph">Control Flow
Graph</a>. Since we
don&#8217;t have any control flow, our functions will only contain one block
at this point. We&#8217;ll fix this in <a class="reference external" href="LangImpl5.html">Chapter 5</a> :).</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="k">if</span> <span class="p">(</span><span class="n">Value</span> <span class="o">*</span><span class="n">RetVal</span> <span class="o">=</span> <span class="n">Body</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">())</span> <span class="p">{</span>
  <span class="c1">// Finish off the function.</span>
  <span class="n">Builder</span><span class="p">.</span><span class="n">CreateRet</span><span class="p">(</span><span class="n">RetVal</span><span class="p">);</span>

  <span class="c1">// Validate the generated code, checking for consistency.</span>
  <span class="n">verifyFunction</span><span class="p">(</span><span class="o">*</span><span class="n">TheFunction</span><span class="p">);</span>

  <span class="k">return</span> <span class="n">TheFunction</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Once the insertion point is set up, we call the <code class="docutils literal"><span class="pre">CodeGen()</span></code> method for
the root expression of the function. If no error happens, this emits
code to compute the expression into the entry block and returns the
value that was computed. Assuming no error, we then create an LLVM <a class="reference external" href="../LangRef.html#i_ret">ret
instruction</a>, which completes the function.
Once the function is built, we call <code class="docutils literal"><span class="pre">verifyFunction</span></code>, which is
provided by LLVM. This function does a variety of consistency checks on
the generated code, to determine if our compiler is doing everything
right. Using this is important: it can catch a lot of bugs. Once the
function is finished and validated, we return it.</p>
<div class="highlight-c++"><div class="highlight"><pre>  <span class="c1">// Error reading body, remove function.</span>
  <span class="n">TheFunction</span><span class="o">-&gt;</span><span class="n">eraseFromParent</span><span class="p">();</span>
  <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The only piece left here is handling of the error case. For simplicity,
we handle this by merely deleting the function we produced with the
<code class="docutils literal"><span class="pre">eraseFromParent</span></code> method. This allows the user to redefine a function
that they incorrectly typed in before: if we didn&#8217;t delete it, it would
live in the symbol table, with a body, preventing future redefinition.</p>
<p>This code does have a bug, though. Since the <code class="docutils literal"><span class="pre">PrototypeAST::Codegen</span></code>
can return a previously defined forward declaration, our code can
actually delete a forward declaration. There are a number of ways to fix
this bug, see what you can come up with! Here is a testcase:</p>
<div class="highlight-python"><div class="highlight"><pre>extern foo(a b);     # ok, defines foo.
def foo(a b) c;      # error, &#39;c&#39; is invalid.
def bar() foo(1, 2); # error, unknown function &quot;foo&quot;
</pre></div>
</div>
</div>
<div class="section" id="driver-changes-and-closing-thoughts">
<h2><a class="toc-backref" href="#id5">3.5. Driver Changes and Closing Thoughts</a><a class="headerlink" href="#driver-changes-and-closing-thoughts" title="Permalink to this headline">¶</a></h2>
<p>For now, code generation to LLVM doesn&#8217;t really get us much, except that
we can look at the pretty IR calls. The sample code inserts calls to
Codegen into the &#8220;<code class="docutils literal"><span class="pre">HandleDefinition</span></code>&#8221;, &#8220;<code class="docutils literal"><span class="pre">HandleExtern</span></code>&#8221; etc
functions, and then dumps out the LLVM IR. This gives a nice way to look
at the LLVM IR for simple functions. For example:</p>
<div class="highlight-python"><div class="highlight"><pre>ready&gt; 4+5;
Read top-level expression:
define double @0() {
entry:
  ret double 9.000000e+00
}
</pre></div>
</div>
<p>Note how the parser turns the top-level expression into anonymous
functions for us. This will be handy when we add <a class="reference external" href="LangImpl4.html#jit">JIT
support</a> in the next chapter. Also note that the
code is very literally transcribed, no optimizations are being performed
except simple constant folding done by IRBuilder. We will <a class="reference external" href="LangImpl4.html#trivialconstfold">add
optimizations</a> explicitly in the next
chapter.</p>
<div class="highlight-python"><div class="highlight"><pre>ready&gt; def foo(a b) a*a + 2*a*b + b*b;
Read function definition:
define double @foo(double %a, double %b) {
entry:
  %multmp = fmul double %a, %a
  %multmp1 = fmul double 2.000000e+00, %a
  %multmp2 = fmul double %multmp1, %b
  %addtmp = fadd double %multmp, %multmp2
  %multmp3 = fmul double %b, %b
  %addtmp4 = fadd double %addtmp, %multmp3
  ret double %addtmp4
}
</pre></div>
</div>
<p>This shows some simple arithmetic. Notice the striking similarity to the
LLVM builder calls that we use to create the instructions.</p>
<div class="highlight-python"><div class="highlight"><pre>ready&gt; def bar(a) foo(a, 4.0) + bar(31337);
Read function definition:
define double @bar(double %a) {
entry:
  %calltmp = call double @foo(double %a, double 4.000000e+00)
  %calltmp1 = call double @bar(double 3.133700e+04)
  %addtmp = fadd double %calltmp, %calltmp1
  ret double %addtmp
}
</pre></div>
</div>
<p>This shows some function calls. Note that this function will take a long
time to execute if you call it. In the future we&#8217;ll add conditional
control flow to actually make recursion useful :).</p>
<div class="highlight-python"><div class="highlight"><pre>ready&gt; extern cos(x);
Read extern:
declare double @cos(double)

ready&gt; cos(1.234);
Read top-level expression:
define double @1() {
entry:
  %calltmp = call double @cos(double 1.234000e+00)
  ret double %calltmp
}
</pre></div>
</div>
<p>This shows an extern for the libm &#8220;cos&#8221; function, and a call to it.</p>
<div class="highlight-python"><div class="highlight"><pre>ready&gt; ^D
; ModuleID = &#39;my cool jit&#39;

define double @0() {
entry:
  %addtmp = fadd double 4.000000e+00, 5.000000e+00
  ret double %addtmp
}

define double @foo(double %a, double %b) {
entry:
  %multmp = fmul double %a, %a
  %multmp1 = fmul double 2.000000e+00, %a
  %multmp2 = fmul double %multmp1, %b
  %addtmp = fadd double %multmp, %multmp2
  %multmp3 = fmul double %b, %b
  %addtmp4 = fadd double %addtmp, %multmp3
  ret double %addtmp4
}

define double @bar(double %a) {
entry:
  %calltmp = call double @foo(double %a, double 4.000000e+00)
  %calltmp1 = call double @bar(double 3.133700e+04)
  %addtmp = fadd double %calltmp, %calltmp1
  ret double %addtmp
}

declare double @cos(double)

define double @1() {
entry:
  %calltmp = call double @cos(double 1.234000e+00)
  ret double %calltmp
}
</pre></div>
</div>
<p>When you quit the current demo, it dumps out the IR for the entire
module generated. Here you can see the big picture with all the
functions referencing each other.</p>
<p>This wraps up the third chapter of the Kaleidoscope tutorial. Up next,
we&#8217;ll describe how to <a class="reference external" href="LangImpl4.html">add JIT codegen and optimizer
support</a> to this so we can actually start running
code!</p>
</div>
<div class="section" id="full-code-listing">
<h2><a class="toc-backref" href="#id6">3.6. Full Code Listing</a><a class="headerlink" href="#full-code-listing" title="Permalink to this headline">¶</a></h2>
<p>Here is the complete code listing for our running example, enhanced with
the LLVM code generator. Because this uses the LLVM libraries, we need
to link them in. To do this, we use the
<a class="reference external" href="http://llvm.org/cmds/llvm-config.html">llvm-config</a> tool to inform
our makefile/command line about which options to use:</p>
<div class="highlight-bash"><div class="highlight"><pre><span class="c"># Compile</span>
clang++ -g -O3 toy.cpp <span class="sb">`</span>llvm-config --cxxflags --ldflags --system-libs --libs core<span class="sb">`</span> -o toy
<span class="c"># Run</span>
./toy
</pre></div>
</div>
<p>Here is the code:</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="cp">#include &quot;llvm/IR/Verifier.h&quot;</span>
<span class="cp">#include &quot;llvm/IR/DerivedTypes.h&quot;</span>
<span class="cp">#include &quot;llvm/IR/IRBuilder.h&quot;</span>
<span class="cp">#include &quot;llvm/IR/LLVMContext.h&quot;</span>
<span class="cp">#include &quot;llvm/IR/Module.h&quot;</span>
<span class="cp">#include &lt;cctype&gt;</span>
<span class="cp">#include &lt;cstdio&gt;</span>
<span class="cp">#include &lt;map&gt;</span>
<span class="cp">#include &lt;string&gt;</span>
<span class="cp">#include &lt;vector&gt;</span>
<span class="k">using</span> <span class="k">namespace</span> <span class="n">llvm</span><span class="p">;</span>

<span class="c1">//===----------------------------------------------------------------------===//</span>
<span class="c1">// Lexer</span>
<span class="c1">//===----------------------------------------------------------------------===//</span>

<span class="c1">// The lexer returns tokens [0-255] if it is an unknown character, otherwise one</span>
<span class="c1">// of these for known things.</span>
<span class="k">enum</span> <span class="n">Token</span> <span class="p">{</span>
  <span class="n">tok_eof</span> <span class="o">=</span> <span class="o">-</span><span class="mi">1</span><span class="p">,</span>

  <span class="c1">// commands</span>
  <span class="n">tok_def</span> <span class="o">=</span> <span class="o">-</span><span class="mi">2</span><span class="p">,</span> <span class="n">tok_extern</span> <span class="o">=</span> <span class="o">-</span><span class="mi">3</span><span class="p">,</span>

  <span class="c1">// primary</span>
  <span class="n">tok_identifier</span> <span class="o">=</span> <span class="o">-</span><span class="mi">4</span><span class="p">,</span> <span class="n">tok_number</span> <span class="o">=</span> <span class="o">-</span><span class="mi">5</span>
<span class="p">};</span>

<span class="k">static</span> <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">IdentifierStr</span><span class="p">;</span>  <span class="c1">// Filled in if tok_identifier</span>
<span class="k">static</span> <span class="kt">double</span> <span class="n">NumVal</span><span class="p">;</span>              <span class="c1">// Filled in if tok_number</span>

<span class="c1">/// gettok - Return the next token from standard input.</span>
<span class="k">static</span> <span class="kt">int</span> <span class="nf">gettok</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">static</span> <span class="kt">int</span> <span class="n">LastChar</span> <span class="o">=</span> <span class="sc">&#39; &#39;</span><span class="p">;</span>

  <span class="c1">// Skip any whitespace.</span>
  <span class="k">while</span> <span class="p">(</span><span class="n">isspace</span><span class="p">(</span><span class="n">LastChar</span><span class="p">))</span>
    <span class="n">LastChar</span> <span class="o">=</span> <span class="n">getchar</span><span class="p">();</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">isalpha</span><span class="p">(</span><span class="n">LastChar</span><span class="p">))</span> <span class="p">{</span> <span class="c1">// identifier: [a-zA-Z][a-zA-Z0-9]*</span>
    <span class="n">IdentifierStr</span> <span class="o">=</span> <span class="n">LastChar</span><span class="p">;</span>
    <span class="k">while</span> <span class="p">(</span><span class="n">isalnum</span><span class="p">((</span><span class="n">LastChar</span> <span class="o">=</span> <span class="n">getchar</span><span class="p">())))</span>
      <span class="n">IdentifierStr</span> <span class="o">+=</span> <span class="n">LastChar</span><span class="p">;</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">IdentifierStr</span> <span class="o">==</span> <span class="s">&quot;def&quot;</span><span class="p">)</span> <span class="k">return</span> <span class="n">tok_def</span><span class="p">;</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">IdentifierStr</span> <span class="o">==</span> <span class="s">&quot;extern&quot;</span><span class="p">)</span> <span class="k">return</span> <span class="n">tok_extern</span><span class="p">;</span>
    <span class="k">return</span> <span class="n">tok_identifier</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">isdigit</span><span class="p">(</span><span class="n">LastChar</span><span class="p">)</span> <span class="o">||</span> <span class="n">LastChar</span> <span class="o">==</span> <span class="sc">&#39;.&#39;</span><span class="p">)</span> <span class="p">{</span>   <span class="c1">// Number: [0-9.]+</span>
    <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">NumStr</span><span class="p">;</span>
    <span class="k">do</span> <span class="p">{</span>
      <span class="n">NumStr</span> <span class="o">+=</span> <span class="n">LastChar</span><span class="p">;</span>
      <span class="n">LastChar</span> <span class="o">=</span> <span class="n">getchar</span><span class="p">();</span>
    <span class="p">}</span> <span class="k">while</span> <span class="p">(</span><span class="n">isdigit</span><span class="p">(</span><span class="n">LastChar</span><span class="p">)</span> <span class="o">||</span> <span class="n">LastChar</span> <span class="o">==</span> <span class="sc">&#39;.&#39;</span><span class="p">);</span>

    <span class="n">NumVal</span> <span class="o">=</span> <span class="n">strtod</span><span class="p">(</span><span class="n">NumStr</span><span class="p">.</span><span class="n">c_str</span><span class="p">(),</span> <span class="mi">0</span><span class="p">);</span>
    <span class="k">return</span> <span class="n">tok_number</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">LastChar</span> <span class="o">==</span> <span class="sc">&#39;#&#39;</span><span class="p">)</span> <span class="p">{</span>
    <span class="c1">// Comment until end of line.</span>
    <span class="k">do</span> <span class="n">LastChar</span> <span class="o">=</span> <span class="n">getchar</span><span class="p">();</span>
    <span class="k">while</span> <span class="p">(</span><span class="n">LastChar</span> <span class="o">!=</span> <span class="n">EOF</span> <span class="o">&amp;&amp;</span> <span class="n">LastChar</span> <span class="o">!=</span> <span class="sc">&#39;\n&#39;</span> <span class="o">&amp;&amp;</span> <span class="n">LastChar</span> <span class="o">!=</span> <span class="sc">&#39;\r&#39;</span><span class="p">);</span>
    
    <span class="k">if</span> <span class="p">(</span><span class="n">LastChar</span> <span class="o">!=</span> <span class="n">EOF</span><span class="p">)</span>
      <span class="k">return</span> <span class="n">gettok</span><span class="p">();</span>
  <span class="p">}</span>
  
  <span class="c1">// Check for end of file.  Don&#39;t eat the EOF.</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">LastChar</span> <span class="o">==</span> <span class="n">EOF</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">tok_eof</span><span class="p">;</span>

  <span class="c1">// Otherwise, just return the character as its ascii value.</span>
  <span class="kt">int</span> <span class="n">ThisChar</span> <span class="o">=</span> <span class="n">LastChar</span><span class="p">;</span>
  <span class="n">LastChar</span> <span class="o">=</span> <span class="n">getchar</span><span class="p">();</span>
  <span class="k">return</span> <span class="n">ThisChar</span><span class="p">;</span>
<span class="p">}</span>

<span class="c1">//===----------------------------------------------------------------------===//</span>
<span class="c1">// Abstract Syntax Tree (aka Parse Tree)</span>
<span class="c1">//===----------------------------------------------------------------------===//</span>
<span class="k">namespace</span> <span class="p">{</span>
<span class="c1">/// ExprAST - Base class for all expression nodes.</span>
<span class="k">class</span> <span class="nc">ExprAST</span> <span class="p">{</span>
<span class="k">public</span><span class="o">:</span>
  <span class="k">virtual</span> <span class="o">~</span><span class="n">ExprAST</span><span class="p">()</span> <span class="p">{}</span>
  <span class="k">virtual</span> <span class="n">Value</span> <span class="o">*</span><span class="n">Codegen</span><span class="p">()</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">};</span>

<span class="c1">/// NumberExprAST - Expression class for numeric literals like &quot;1.0&quot;.</span>
<span class="k">class</span> <span class="nc">NumberExprAST</span> <span class="o">:</span> <span class="k">public</span> <span class="n">ExprAST</span> <span class="p">{</span>
  <span class="kt">double</span> <span class="n">Val</span><span class="p">;</span>
<span class="k">public</span><span class="o">:</span>
  <span class="n">NumberExprAST</span><span class="p">(</span><span class="kt">double</span> <span class="n">val</span><span class="p">)</span> <span class="o">:</span> <span class="n">Val</span><span class="p">(</span><span class="n">val</span><span class="p">)</span> <span class="p">{}</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">Codegen</span><span class="p">()</span> <span class="k">override</span><span class="p">;</span>
<span class="p">};</span>

<span class="c1">/// VariableExprAST - Expression class for referencing a variable, like &quot;a&quot;.</span>
<span class="k">class</span> <span class="nc">VariableExprAST</span> <span class="o">:</span> <span class="k">public</span> <span class="n">ExprAST</span> <span class="p">{</span>
  <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">Name</span><span class="p">;</span>
<span class="k">public</span><span class="o">:</span>
  <span class="n">VariableExprAST</span><span class="p">(</span><span class="k">const</span> <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="o">&amp;</span><span class="n">name</span><span class="p">)</span> <span class="o">:</span> <span class="n">Name</span><span class="p">(</span><span class="n">name</span><span class="p">)</span> <span class="p">{}</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">Codegen</span><span class="p">()</span> <span class="k">override</span><span class="p">;</span>
<span class="p">};</span>

<span class="c1">/// BinaryExprAST - Expression class for a binary operator.</span>
<span class="k">class</span> <span class="nc">BinaryExprAST</span> <span class="o">:</span> <span class="k">public</span> <span class="n">ExprAST</span> <span class="p">{</span>
  <span class="kt">char</span> <span class="n">Op</span><span class="p">;</span>
  <span class="n">ExprAST</span> <span class="o">*</span><span class="n">LHS</span><span class="p">,</span> <span class="o">*</span><span class="n">RHS</span><span class="p">;</span>
<span class="k">public</span><span class="o">:</span>
  <span class="n">BinaryExprAST</span><span class="p">(</span><span class="kt">char</span> <span class="n">op</span><span class="p">,</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="n">lhs</span><span class="p">,</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="n">rhs</span><span class="p">)</span> 
    <span class="o">:</span> <span class="n">Op</span><span class="p">(</span><span class="n">op</span><span class="p">),</span> <span class="n">LHS</span><span class="p">(</span><span class="n">lhs</span><span class="p">),</span> <span class="n">RHS</span><span class="p">(</span><span class="n">rhs</span><span class="p">)</span> <span class="p">{}</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">Codegen</span><span class="p">()</span> <span class="k">override</span><span class="p">;</span>
<span class="p">};</span>

<span class="c1">/// CallExprAST - Expression class for function calls.</span>
<span class="k">class</span> <span class="nc">CallExprAST</span> <span class="o">:</span> <span class="k">public</span> <span class="n">ExprAST</span> <span class="p">{</span>
  <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">Callee</span><span class="p">;</span>
  <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">ExprAST</span><span class="o">*&gt;</span> <span class="n">Args</span><span class="p">;</span>
<span class="k">public</span><span class="o">:</span>
  <span class="n">CallExprAST</span><span class="p">(</span><span class="k">const</span> <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="o">&amp;</span><span class="n">callee</span><span class="p">,</span> <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">ExprAST</span><span class="o">*&gt;</span> <span class="o">&amp;</span><span class="n">args</span><span class="p">)</span>
    <span class="o">:</span> <span class="n">Callee</span><span class="p">(</span><span class="n">callee</span><span class="p">),</span> <span class="n">Args</span><span class="p">(</span><span class="n">args</span><span class="p">)</span> <span class="p">{}</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">Codegen</span><span class="p">()</span> <span class="k">override</span><span class="p">;</span>
<span class="p">};</span>

<span class="c1">/// PrototypeAST - This class represents the &quot;prototype&quot; for a function,</span>
<span class="c1">/// which captures its name, and its argument names (thus implicitly the number</span>
<span class="c1">/// of arguments the function takes).</span>
<span class="k">class</span> <span class="nc">PrototypeAST</span> <span class="p">{</span>
  <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">Name</span><span class="p">;</span>
  <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">&gt;</span> <span class="n">Args</span><span class="p">;</span>
<span class="k">public</span><span class="o">:</span>
  <span class="n">PrototypeAST</span><span class="p">(</span><span class="k">const</span> <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="o">&amp;</span><span class="n">name</span><span class="p">,</span> <span class="k">const</span> <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">&gt;</span> <span class="o">&amp;</span><span class="n">args</span><span class="p">)</span>
    <span class="o">:</span> <span class="n">Name</span><span class="p">(</span><span class="n">name</span><span class="p">),</span> <span class="n">Args</span><span class="p">(</span><span class="n">args</span><span class="p">)</span> <span class="p">{}</span>
  
  <span class="n">Function</span> <span class="o">*</span><span class="n">Codegen</span><span class="p">();</span>
<span class="p">};</span>

<span class="c1">/// FunctionAST - This class represents a function definition itself.</span>
<span class="k">class</span> <span class="nc">FunctionAST</span> <span class="p">{</span>
  <span class="n">PrototypeAST</span> <span class="o">*</span><span class="n">Proto</span><span class="p">;</span>
  <span class="n">ExprAST</span> <span class="o">*</span><span class="n">Body</span><span class="p">;</span>
<span class="k">public</span><span class="o">:</span>
  <span class="n">FunctionAST</span><span class="p">(</span><span class="n">PrototypeAST</span> <span class="o">*</span><span class="n">proto</span><span class="p">,</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="n">body</span><span class="p">)</span>
    <span class="o">:</span> <span class="n">Proto</span><span class="p">(</span><span class="n">proto</span><span class="p">),</span> <span class="n">Body</span><span class="p">(</span><span class="n">body</span><span class="p">)</span> <span class="p">{}</span>
  
  <span class="n">Function</span> <span class="o">*</span><span class="n">Codegen</span><span class="p">();</span>
<span class="p">};</span>
<span class="p">}</span> <span class="c1">// end anonymous namespace</span>

<span class="c1">//===----------------------------------------------------------------------===//</span>
<span class="c1">// Parser</span>
<span class="c1">//===----------------------------------------------------------------------===//</span>

<span class="c1">/// CurTok/getNextToken - Provide a simple token buffer.  CurTok is the current</span>
<span class="c1">/// token the parser is looking at.  getNextToken reads another token from the</span>
<span class="c1">/// lexer and updates CurTok with its results.</span>
<span class="k">static</span> <span class="kt">int</span> <span class="n">CurTok</span><span class="p">;</span>
<span class="k">static</span> <span class="kt">int</span> <span class="nf">getNextToken</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">return</span> <span class="n">CurTok</span> <span class="o">=</span> <span class="n">gettok</span><span class="p">();</span>
<span class="p">}</span>

<span class="c1">/// BinopPrecedence - This holds the precedence for each binary operator that is</span>
<span class="c1">/// defined.</span>
<span class="k">static</span> <span class="n">std</span><span class="o">::</span><span class="n">map</span><span class="o">&lt;</span><span class="kt">char</span><span class="p">,</span> <span class="kt">int</span><span class="o">&gt;</span> <span class="n">BinopPrecedence</span><span class="p">;</span>

<span class="c1">/// GetTokPrecedence - Get the precedence of the pending binary operator token.</span>
<span class="k">static</span> <span class="kt">int</span> <span class="nf">GetTokPrecedence</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">isascii</span><span class="p">(</span><span class="n">CurTok</span><span class="p">))</span>
    <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
  
  <span class="c1">// Make sure it&#39;s a declared binop.</span>
  <span class="kt">int</span> <span class="n">TokPrec</span> <span class="o">=</span> <span class="n">BinopPrecedence</span><span class="p">[</span><span class="n">CurTok</span><span class="p">];</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">TokPrec</span> <span class="o">&lt;=</span> <span class="mi">0</span><span class="p">)</span> <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
  <span class="k">return</span> <span class="n">TokPrec</span><span class="p">;</span>
<span class="p">}</span>

<span class="c1">/// Error* - These are little helper functions for error handling.</span>
<span class="n">ExprAST</span> <span class="o">*</span><span class="nf">Error</span><span class="p">(</span><span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">Str</span><span class="p">)</span> <span class="p">{</span> <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&quot;Error: %s</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">,</span> <span class="n">Str</span><span class="p">);</span><span class="k">return</span> <span class="mi">0</span><span class="p">;}</span>
<span class="n">PrototypeAST</span> <span class="o">*</span><span class="nf">ErrorP</span><span class="p">(</span><span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">Str</span><span class="p">)</span> <span class="p">{</span> <span class="n">Error</span><span class="p">(</span><span class="n">Str</span><span class="p">);</span> <span class="k">return</span> <span class="mi">0</span><span class="p">;</span> <span class="p">}</span>
<span class="n">FunctionAST</span> <span class="o">*</span><span class="nf">ErrorF</span><span class="p">(</span><span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">Str</span><span class="p">)</span> <span class="p">{</span> <span class="n">Error</span><span class="p">(</span><span class="n">Str</span><span class="p">);</span> <span class="k">return</span> <span class="mi">0</span><span class="p">;</span> <span class="p">}</span>

<span class="k">static</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="nf">ParseExpression</span><span class="p">();</span>

<span class="c1">/// identifierexpr</span>
<span class="c1">///   ::= identifier</span>
<span class="c1">///   ::= identifier &#39;(&#39; expression* &#39;)&#39;</span>
<span class="k">static</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="nf">ParseIdentifierExpr</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">IdName</span> <span class="o">=</span> <span class="n">IdentifierStr</span><span class="p">;</span>
  
  <span class="n">getNextToken</span><span class="p">();</span>  <span class="c1">// eat identifier.</span>
  
  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="sc">&#39;(&#39;</span><span class="p">)</span> <span class="c1">// Simple variable ref.</span>
    <span class="k">return</span> <span class="k">new</span> <span class="n">VariableExprAST</span><span class="p">(</span><span class="n">IdName</span><span class="p">);</span>
  
  <span class="c1">// Call.</span>
  <span class="n">getNextToken</span><span class="p">();</span>  <span class="c1">// eat (</span>
  <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">ExprAST</span><span class="o">*&gt;</span> <span class="n">Args</span><span class="p">;</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="sc">&#39;)&#39;</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">while</span> <span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
      <span class="n">ExprAST</span> <span class="o">*</span><span class="n">Arg</span> <span class="o">=</span> <span class="n">ParseExpression</span><span class="p">();</span>
      <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">Arg</span><span class="p">)</span> <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
      <span class="n">Args</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="n">Arg</span><span class="p">);</span>

      <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">==</span> <span class="sc">&#39;)&#39;</span><span class="p">)</span> <span class="k">break</span><span class="p">;</span>

      <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="sc">&#39;,&#39;</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">Error</span><span class="p">(</span><span class="s">&quot;Expected &#39;)&#39; or &#39;,&#39; in argument list&quot;</span><span class="p">);</span>
      <span class="n">getNextToken</span><span class="p">();</span>
    <span class="p">}</span>
  <span class="p">}</span>

  <span class="c1">// Eat the &#39;)&#39;.</span>
  <span class="n">getNextToken</span><span class="p">();</span>
  
  <span class="k">return</span> <span class="k">new</span> <span class="n">CallExprAST</span><span class="p">(</span><span class="n">IdName</span><span class="p">,</span> <span class="n">Args</span><span class="p">);</span>
<span class="p">}</span>

<span class="c1">/// numberexpr ::= number</span>
<span class="k">static</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="nf">ParseNumberExpr</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">ExprAST</span> <span class="o">*</span><span class="n">Result</span> <span class="o">=</span> <span class="k">new</span> <span class="n">NumberExprAST</span><span class="p">(</span><span class="n">NumVal</span><span class="p">);</span>
  <span class="n">getNextToken</span><span class="p">();</span> <span class="c1">// consume the number</span>
  <span class="k">return</span> <span class="n">Result</span><span class="p">;</span>
<span class="p">}</span>

<span class="c1">/// parenexpr ::= &#39;(&#39; expression &#39;)&#39;</span>
<span class="k">static</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="nf">ParseParenExpr</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">getNextToken</span><span class="p">();</span>  <span class="c1">// eat (.</span>
  <span class="n">ExprAST</span> <span class="o">*</span><span class="n">V</span> <span class="o">=</span> <span class="n">ParseExpression</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">V</span><span class="p">)</span> <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
  
  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="sc">&#39;)&#39;</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">Error</span><span class="p">(</span><span class="s">&quot;expected &#39;)&#39;&quot;</span><span class="p">);</span>
  <span class="n">getNextToken</span><span class="p">();</span>  <span class="c1">// eat ).</span>
  <span class="k">return</span> <span class="n">V</span><span class="p">;</span>
<span class="p">}</span>

<span class="c1">/// primary</span>
<span class="c1">///   ::= identifierexpr</span>
<span class="c1">///   ::= numberexpr</span>
<span class="c1">///   ::= parenexpr</span>
<span class="k">static</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="nf">ParsePrimary</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">switch</span> <span class="p">(</span><span class="n">CurTok</span><span class="p">)</span> <span class="p">{</span>
  <span class="k">default</span><span class="o">:</span> <span class="k">return</span> <span class="n">Error</span><span class="p">(</span><span class="s">&quot;unknown token when expecting an expression&quot;</span><span class="p">);</span>
  <span class="k">case</span> <span class="nl">tok_identifier</span><span class="p">:</span> <span class="k">return</span> <span class="n">ParseIdentifierExpr</span><span class="p">();</span>
  <span class="k">case</span> <span class="nl">tok_number</span><span class="p">:</span>     <span class="k">return</span> <span class="n">ParseNumberExpr</span><span class="p">();</span>
  <span class="k">case</span> <span class="sc">&#39;(&#39;</span><span class="o">:</span>            <span class="k">return</span> <span class="n">ParseParenExpr</span><span class="p">();</span>
  <span class="p">}</span>
<span class="p">}</span>

<span class="c1">/// binoprhs</span>
<span class="c1">///   ::= (&#39;+&#39; primary)*</span>
<span class="k">static</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="nf">ParseBinOpRHS</span><span class="p">(</span><span class="kt">int</span> <span class="n">ExprPrec</span><span class="p">,</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="n">LHS</span><span class="p">)</span> <span class="p">{</span>
  <span class="c1">// If this is a binop, find its precedence.</span>
  <span class="k">while</span> <span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
    <span class="kt">int</span> <span class="n">TokPrec</span> <span class="o">=</span> <span class="n">GetTokPrecedence</span><span class="p">();</span>
    
    <span class="c1">// If this is a binop that binds at least as tightly as the current binop,</span>
    <span class="c1">// consume it, otherwise we are done.</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">TokPrec</span> <span class="o">&lt;</span> <span class="n">ExprPrec</span><span class="p">)</span>
      <span class="k">return</span> <span class="n">LHS</span><span class="p">;</span>
    
    <span class="c1">// Okay, we know this is a binop.</span>
    <span class="kt">int</span> <span class="n">BinOp</span> <span class="o">=</span> <span class="n">CurTok</span><span class="p">;</span>
    <span class="n">getNextToken</span><span class="p">();</span>  <span class="c1">// eat binop</span>
    
    <span class="c1">// Parse the primary expression after the binary operator.</span>
    <span class="n">ExprAST</span> <span class="o">*</span><span class="n">RHS</span> <span class="o">=</span> <span class="n">ParsePrimary</span><span class="p">();</span>
    <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">RHS</span><span class="p">)</span> <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
    
    <span class="c1">// If BinOp binds less tightly with RHS than the operator after RHS, let</span>
    <span class="c1">// the pending operator take RHS as its LHS.</span>
    <span class="kt">int</span> <span class="n">NextPrec</span> <span class="o">=</span> <span class="n">GetTokPrecedence</span><span class="p">();</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">TokPrec</span> <span class="o">&lt;</span> <span class="n">NextPrec</span><span class="p">)</span> <span class="p">{</span>
      <span class="n">RHS</span> <span class="o">=</span> <span class="n">ParseBinOpRHS</span><span class="p">(</span><span class="n">TokPrec</span><span class="o">+</span><span class="mi">1</span><span class="p">,</span> <span class="n">RHS</span><span class="p">);</span>
      <span class="k">if</span> <span class="p">(</span><span class="n">RHS</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span> <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
    <span class="p">}</span>
    
    <span class="c1">// Merge LHS/RHS.</span>
    <span class="n">LHS</span> <span class="o">=</span> <span class="k">new</span> <span class="n">BinaryExprAST</span><span class="p">(</span><span class="n">BinOp</span><span class="p">,</span> <span class="n">LHS</span><span class="p">,</span> <span class="n">RHS</span><span class="p">);</span>
  <span class="p">}</span>
<span class="p">}</span>

<span class="c1">/// expression</span>
<span class="c1">///   ::= primary binoprhs</span>
<span class="c1">///</span>
<span class="k">static</span> <span class="n">ExprAST</span> <span class="o">*</span><span class="nf">ParseExpression</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">ExprAST</span> <span class="o">*</span><span class="n">LHS</span> <span class="o">=</span> <span class="n">ParsePrimary</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">LHS</span><span class="p">)</span> <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
  
  <span class="k">return</span> <span class="n">ParseBinOpRHS</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">LHS</span><span class="p">);</span>
<span class="p">}</span>

<span class="c1">/// prototype</span>
<span class="c1">///   ::= id &#39;(&#39; id* &#39;)&#39;</span>
<span class="k">static</span> <span class="n">PrototypeAST</span> <span class="o">*</span><span class="nf">ParsePrototype</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="n">tok_identifier</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">ErrorP</span><span class="p">(</span><span class="s">&quot;Expected function name in prototype&quot;</span><span class="p">);</span>

  <span class="n">std</span><span class="o">::</span><span class="n">string</span> <span class="n">FnName</span> <span class="o">=</span> <span class="n">IdentifierStr</span><span class="p">;</span>
  <span class="n">getNextToken</span><span class="p">();</span>
  
  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="sc">&#39;(&#39;</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">ErrorP</span><span class="p">(</span><span class="s">&quot;Expected &#39;(&#39; in prototype&quot;</span><span class="p">);</span>
  
  <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">&gt;</span> <span class="n">ArgNames</span><span class="p">;</span>
  <span class="k">while</span> <span class="p">(</span><span class="n">getNextToken</span><span class="p">()</span> <span class="o">==</span> <span class="n">tok_identifier</span><span class="p">)</span>
    <span class="n">ArgNames</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="n">IdentifierStr</span><span class="p">);</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">CurTok</span> <span class="o">!=</span> <span class="sc">&#39;)&#39;</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">ErrorP</span><span class="p">(</span><span class="s">&quot;Expected &#39;)&#39; in prototype&quot;</span><span class="p">);</span>
  
  <span class="c1">// success.</span>
  <span class="n">getNextToken</span><span class="p">();</span>  <span class="c1">// eat &#39;)&#39;.</span>
  
  <span class="k">return</span> <span class="k">new</span> <span class="n">PrototypeAST</span><span class="p">(</span><span class="n">FnName</span><span class="p">,</span> <span class="n">ArgNames</span><span class="p">);</span>
<span class="p">}</span>

<span class="c1">/// definition ::= &#39;def&#39; prototype expression</span>
<span class="k">static</span> <span class="n">FunctionAST</span> <span class="o">*</span><span class="nf">ParseDefinition</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">getNextToken</span><span class="p">();</span>  <span class="c1">// eat def.</span>
  <span class="n">PrototypeAST</span> <span class="o">*</span><span class="n">Proto</span> <span class="o">=</span> <span class="n">ParsePrototype</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">Proto</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span> <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>

  <span class="k">if</span> <span class="p">(</span><span class="n">ExprAST</span> <span class="o">*</span><span class="n">E</span> <span class="o">=</span> <span class="n">ParseExpression</span><span class="p">())</span>
    <span class="k">return</span> <span class="k">new</span> <span class="n">FunctionAST</span><span class="p">(</span><span class="n">Proto</span><span class="p">,</span> <span class="n">E</span><span class="p">);</span>
  <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>

<span class="c1">/// toplevelexpr ::= expression</span>
<span class="k">static</span> <span class="n">FunctionAST</span> <span class="o">*</span><span class="nf">ParseTopLevelExpr</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">ExprAST</span> <span class="o">*</span><span class="n">E</span> <span class="o">=</span> <span class="n">ParseExpression</span><span class="p">())</span> <span class="p">{</span>
    <span class="c1">// Make an anonymous proto.</span>
    <span class="n">PrototypeAST</span> <span class="o">*</span><span class="n">Proto</span> <span class="o">=</span> <span class="k">new</span> <span class="n">PrototypeAST</span><span class="p">(</span><span class="s">&quot;&quot;</span><span class="p">,</span> <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="o">&gt;</span><span class="p">());</span>
    <span class="k">return</span> <span class="k">new</span> <span class="n">FunctionAST</span><span class="p">(</span><span class="n">Proto</span><span class="p">,</span> <span class="n">E</span><span class="p">);</span>
  <span class="p">}</span>
  <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>

<span class="c1">/// external ::= &#39;extern&#39; prototype</span>
<span class="k">static</span> <span class="n">PrototypeAST</span> <span class="o">*</span><span class="nf">ParseExtern</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">getNextToken</span><span class="p">();</span>  <span class="c1">// eat extern.</span>
  <span class="k">return</span> <span class="n">ParsePrototype</span><span class="p">();</span>
<span class="p">}</span>

<span class="c1">//===----------------------------------------------------------------------===//</span>
<span class="c1">// Code Generation</span>
<span class="c1">//===----------------------------------------------------------------------===//</span>

<span class="k">static</span> <span class="n">Module</span> <span class="o">*</span><span class="n">TheModule</span><span class="p">;</span>
<span class="k">static</span> <span class="n">IRBuilder</span><span class="o">&lt;&gt;</span> <span class="n">Builder</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">());</span>
<span class="k">static</span> <span class="n">std</span><span class="o">::</span><span class="n">map</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">string</span><span class="p">,</span> <span class="n">Value</span><span class="o">*&gt;</span> <span class="n">NamedValues</span><span class="p">;</span>

<span class="n">Value</span> <span class="o">*</span><span class="nf">ErrorV</span><span class="p">(</span><span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">Str</span><span class="p">)</span> <span class="p">{</span> <span class="n">Error</span><span class="p">(</span><span class="n">Str</span><span class="p">);</span> <span class="k">return</span> <span class="mi">0</span><span class="p">;</span> <span class="p">}</span>

<span class="n">Value</span> <span class="o">*</span><span class="n">NumberExprAST</span><span class="o">::</span><span class="n">Codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">return</span> <span class="n">ConstantFP</span><span class="o">::</span><span class="n">get</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">(),</span> <span class="n">APFloat</span><span class="p">(</span><span class="n">Val</span><span class="p">));</span>
<span class="p">}</span>

<span class="n">Value</span> <span class="o">*</span><span class="n">VariableExprAST</span><span class="o">::</span><span class="n">Codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="c1">// Look this variable up in the function.</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">V</span> <span class="o">=</span> <span class="n">NamedValues</span><span class="p">[</span><span class="n">Name</span><span class="p">];</span>
  <span class="k">return</span> <span class="n">V</span> <span class="o">?</span> <span class="nl">V</span> <span class="p">:</span> <span class="n">ErrorV</span><span class="p">(</span><span class="s">&quot;Unknown variable name&quot;</span><span class="p">);</span>
<span class="p">}</span>

<span class="n">Value</span> <span class="o">*</span><span class="n">BinaryExprAST</span><span class="o">::</span><span class="n">Codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">L</span> <span class="o">=</span> <span class="n">LHS</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">();</span>
  <span class="n">Value</span> <span class="o">*</span><span class="n">R</span> <span class="o">=</span> <span class="n">RHS</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">L</span> <span class="o">==</span> <span class="mi">0</span> <span class="o">||</span> <span class="n">R</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span> <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
  
  <span class="k">switch</span> <span class="p">(</span><span class="n">Op</span><span class="p">)</span> <span class="p">{</span>
  <span class="k">case</span> <span class="sc">&#39;+&#39;</span><span class="o">:</span> <span class="k">return</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateFAdd</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">R</span><span class="p">,</span> <span class="s">&quot;addtmp&quot;</span><span class="p">);</span>
  <span class="k">case</span> <span class="sc">&#39;-&#39;</span><span class="o">:</span> <span class="k">return</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateFSub</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">R</span><span class="p">,</span> <span class="s">&quot;subtmp&quot;</span><span class="p">);</span>
  <span class="k">case</span> <span class="sc">&#39;*&#39;</span><span class="o">:</span> <span class="k">return</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateFMul</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">R</span><span class="p">,</span> <span class="s">&quot;multmp&quot;</span><span class="p">);</span>
  <span class="k">case</span> <span class="sc">&#39;&lt;&#39;</span><span class="o">:</span>
    <span class="n">L</span> <span class="o">=</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateFCmpULT</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">R</span><span class="p">,</span> <span class="s">&quot;cmptmp&quot;</span><span class="p">);</span>
    <span class="c1">// Convert bool 0/1 to double 0.0 or 1.0</span>
    <span class="k">return</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateUIToFP</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">Type</span><span class="o">::</span><span class="n">getDoubleTy</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">()),</span>
                                <span class="s">&quot;booltmp&quot;</span><span class="p">);</span>
  <span class="k">default</span><span class="o">:</span> <span class="k">return</span> <span class="n">ErrorV</span><span class="p">(</span><span class="s">&quot;invalid binary operator&quot;</span><span class="p">);</span>
  <span class="p">}</span>
<span class="p">}</span>

<span class="n">Value</span> <span class="o">*</span><span class="n">CallExprAST</span><span class="o">::</span><span class="n">Codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="c1">// Look up the name in the global module table.</span>
  <span class="n">Function</span> <span class="o">*</span><span class="n">CalleeF</span> <span class="o">=</span> <span class="n">TheModule</span><span class="o">-&gt;</span><span class="n">getFunction</span><span class="p">(</span><span class="n">Callee</span><span class="p">);</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">CalleeF</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">ErrorV</span><span class="p">(</span><span class="s">&quot;Unknown function referenced&quot;</span><span class="p">);</span>
  
  <span class="c1">// If argument mismatch error.</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">CalleeF</span><span class="o">-&gt;</span><span class="n">arg_size</span><span class="p">()</span> <span class="o">!=</span> <span class="n">Args</span><span class="p">.</span><span class="n">size</span><span class="p">())</span>
    <span class="k">return</span> <span class="n">ErrorV</span><span class="p">(</span><span class="s">&quot;Incorrect # arguments passed&quot;</span><span class="p">);</span>

  <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">Value</span><span class="o">*&gt;</span> <span class="n">ArgsV</span><span class="p">;</span>
  <span class="k">for</span> <span class="p">(</span><span class="kt">unsigned</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="n">e</span> <span class="o">=</span> <span class="n">Args</span><span class="p">.</span><span class="n">size</span><span class="p">();</span> <span class="n">i</span> <span class="o">!=</span> <span class="n">e</span><span class="p">;</span> <span class="o">++</span><span class="n">i</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">ArgsV</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="n">Args</span><span class="p">[</span><span class="n">i</span><span class="p">]</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">());</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">ArgsV</span><span class="p">.</span><span class="n">back</span><span class="p">()</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span> <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
  <span class="p">}</span>
  
  <span class="k">return</span> <span class="n">Builder</span><span class="p">.</span><span class="n">CreateCall</span><span class="p">(</span><span class="n">CalleeF</span><span class="p">,</span> <span class="n">ArgsV</span><span class="p">,</span> <span class="s">&quot;calltmp&quot;</span><span class="p">);</span>
<span class="p">}</span>

<span class="n">Function</span> <span class="o">*</span><span class="n">PrototypeAST</span><span class="o">::</span><span class="n">Codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="c1">// Make the function type:  double(double,double) etc.</span>
  <span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">Type</span><span class="o">*&gt;</span> <span class="n">Doubles</span><span class="p">(</span><span class="n">Args</span><span class="p">.</span><span class="n">size</span><span class="p">(),</span>
                             <span class="n">Type</span><span class="o">::</span><span class="n">getDoubleTy</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">()));</span>
  <span class="n">FunctionType</span> <span class="o">*</span><span class="n">FT</span> <span class="o">=</span> <span class="n">FunctionType</span><span class="o">::</span><span class="n">get</span><span class="p">(</span><span class="n">Type</span><span class="o">::</span><span class="n">getDoubleTy</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">()),</span>
                                       <span class="n">Doubles</span><span class="p">,</span> <span class="nb">false</span><span class="p">);</span>
  
  <span class="n">Function</span> <span class="o">*</span><span class="n">F</span> <span class="o">=</span> <span class="n">Function</span><span class="o">::</span><span class="n">Create</span><span class="p">(</span><span class="n">FT</span><span class="p">,</span> <span class="n">Function</span><span class="o">::</span><span class="n">ExternalLinkage</span><span class="p">,</span> <span class="n">Name</span><span class="p">,</span> <span class="n">TheModule</span><span class="p">);</span>
  
  <span class="c1">// If F conflicted, there was already something named &#39;Name&#39;.  If it has a</span>
  <span class="c1">// body, don&#39;t allow redefinition or reextern.</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">F</span><span class="o">-&gt;</span><span class="n">getName</span><span class="p">()</span> <span class="o">!=</span> <span class="n">Name</span><span class="p">)</span> <span class="p">{</span>
    <span class="c1">// Delete the one we just made and get the existing one.</span>
    <span class="n">F</span><span class="o">-&gt;</span><span class="n">eraseFromParent</span><span class="p">();</span>
    <span class="n">F</span> <span class="o">=</span> <span class="n">TheModule</span><span class="o">-&gt;</span><span class="n">getFunction</span><span class="p">(</span><span class="n">Name</span><span class="p">);</span>
    
    <span class="c1">// If F already has a body, reject this.</span>
    <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">F</span><span class="o">-&gt;</span><span class="n">empty</span><span class="p">())</span> <span class="p">{</span>
      <span class="n">ErrorF</span><span class="p">(</span><span class="s">&quot;redefinition of function&quot;</span><span class="p">);</span>
      <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
    <span class="p">}</span>
    
    <span class="c1">// If F took a different number of args, reject.</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">F</span><span class="o">-&gt;</span><span class="n">arg_size</span><span class="p">()</span> <span class="o">!=</span> <span class="n">Args</span><span class="p">.</span><span class="n">size</span><span class="p">())</span> <span class="p">{</span>
      <span class="n">ErrorF</span><span class="p">(</span><span class="s">&quot;redefinition of function with different # args&quot;</span><span class="p">);</span>
      <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
    <span class="p">}</span>
  <span class="p">}</span>
  
  <span class="c1">// Set names for all arguments.</span>
  <span class="kt">unsigned</span> <span class="n">Idx</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
  <span class="k">for</span> <span class="p">(</span><span class="n">Function</span><span class="o">::</span><span class="n">arg_iterator</span> <span class="n">AI</span> <span class="o">=</span> <span class="n">F</span><span class="o">-&gt;</span><span class="n">arg_begin</span><span class="p">();</span> <span class="n">Idx</span> <span class="o">!=</span> <span class="n">Args</span><span class="p">.</span><span class="n">size</span><span class="p">();</span>
       <span class="o">++</span><span class="n">AI</span><span class="p">,</span> <span class="o">++</span><span class="n">Idx</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">AI</span><span class="o">-&gt;</span><span class="n">setName</span><span class="p">(</span><span class="n">Args</span><span class="p">[</span><span class="n">Idx</span><span class="p">]);</span>
    
    <span class="c1">// Add arguments to variable symbol table.</span>
    <span class="n">NamedValues</span><span class="p">[</span><span class="n">Args</span><span class="p">[</span><span class="n">Idx</span><span class="p">]]</span> <span class="o">=</span> <span class="n">AI</span><span class="p">;</span>
  <span class="p">}</span>
  
  <span class="k">return</span> <span class="n">F</span><span class="p">;</span>
<span class="p">}</span>

<span class="n">Function</span> <span class="o">*</span><span class="n">FunctionAST</span><span class="o">::</span><span class="n">Codegen</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">NamedValues</span><span class="p">.</span><span class="n">clear</span><span class="p">();</span>
  
  <span class="n">Function</span> <span class="o">*</span><span class="n">TheFunction</span> <span class="o">=</span> <span class="n">Proto</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">();</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">TheFunction</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
  
  <span class="c1">// Create a new basic block to start insertion into.</span>
  <span class="n">BasicBlock</span> <span class="o">*</span><span class="n">BB</span> <span class="o">=</span> <span class="n">BasicBlock</span><span class="o">::</span><span class="n">Create</span><span class="p">(</span><span class="n">getGlobalContext</span><span class="p">(),</span> <span class="s">&quot;entry&quot;</span><span class="p">,</span> <span class="n">TheFunction</span><span class="p">);</span>
  <span class="n">Builder</span><span class="p">.</span><span class="n">SetInsertPoint</span><span class="p">(</span><span class="n">BB</span><span class="p">);</span>
  
  <span class="k">if</span> <span class="p">(</span><span class="n">Value</span> <span class="o">*</span><span class="n">RetVal</span> <span class="o">=</span> <span class="n">Body</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">())</span> <span class="p">{</span>
    <span class="c1">// Finish off the function.</span>
    <span class="n">Builder</span><span class="p">.</span><span class="n">CreateRet</span><span class="p">(</span><span class="n">RetVal</span><span class="p">);</span>

    <span class="c1">// Validate the generated code, checking for consistency.</span>
    <span class="n">verifyFunction</span><span class="p">(</span><span class="o">*</span><span class="n">TheFunction</span><span class="p">);</span>

    <span class="k">return</span> <span class="n">TheFunction</span><span class="p">;</span>
  <span class="p">}</span>
  
  <span class="c1">// Error reading body, remove function.</span>
  <span class="n">TheFunction</span><span class="o">-&gt;</span><span class="n">eraseFromParent</span><span class="p">();</span>
  <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>

<span class="c1">//===----------------------------------------------------------------------===//</span>
<span class="c1">// Top-Level parsing and JIT Driver</span>
<span class="c1">//===----------------------------------------------------------------------===//</span>

<span class="k">static</span> <span class="kt">void</span> <span class="n">HandleDefinition</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">FunctionAST</span> <span class="o">*</span><span class="n">F</span> <span class="o">=</span> <span class="n">ParseDefinition</span><span class="p">())</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">Function</span> <span class="o">*</span><span class="n">LF</span> <span class="o">=</span> <span class="n">F</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">())</span> <span class="p">{</span>
      <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&quot;Read function definition:&quot;</span><span class="p">);</span>
      <span class="n">LF</span><span class="o">-&gt;</span><span class="n">dump</span><span class="p">();</span>
    <span class="p">}</span>
  <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
    <span class="c1">// Skip token for error recovery.</span>
    <span class="n">getNextToken</span><span class="p">();</span>
  <span class="p">}</span>
<span class="p">}</span>

<span class="k">static</span> <span class="kt">void</span> <span class="n">HandleExtern</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">PrototypeAST</span> <span class="o">*</span><span class="n">P</span> <span class="o">=</span> <span class="n">ParseExtern</span><span class="p">())</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">Function</span> <span class="o">*</span><span class="n">F</span> <span class="o">=</span> <span class="n">P</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">())</span> <span class="p">{</span>
      <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&quot;Read extern: &quot;</span><span class="p">);</span>
      <span class="n">F</span><span class="o">-&gt;</span><span class="n">dump</span><span class="p">();</span>
    <span class="p">}</span>
  <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
    <span class="c1">// Skip token for error recovery.</span>
    <span class="n">getNextToken</span><span class="p">();</span>
  <span class="p">}</span>
<span class="p">}</span>

<span class="k">static</span> <span class="kt">void</span> <span class="n">HandleTopLevelExpression</span><span class="p">()</span> <span class="p">{</span>
  <span class="c1">// Evaluate a top-level expression into an anonymous function.</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">FunctionAST</span> <span class="o">*</span><span class="n">F</span> <span class="o">=</span> <span class="n">ParseTopLevelExpr</span><span class="p">())</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">Function</span> <span class="o">*</span><span class="n">LF</span> <span class="o">=</span> <span class="n">F</span><span class="o">-&gt;</span><span class="n">Codegen</span><span class="p">())</span> <span class="p">{</span>
      <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&quot;Read top-level expression:&quot;</span><span class="p">);</span>
      <span class="n">LF</span><span class="o">-&gt;</span><span class="n">dump</span><span class="p">();</span>
    <span class="p">}</span>
  <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
    <span class="c1">// Skip token for error recovery.</span>
    <span class="n">getNextToken</span><span class="p">();</span>
  <span class="p">}</span>
<span class="p">}</span>

<span class="c1">/// top ::= definition | external | expression | &#39;;&#39;</span>
<span class="k">static</span> <span class="kt">void</span> <span class="n">MainLoop</span><span class="p">()</span> <span class="p">{</span>
  <span class="k">while</span> <span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&quot;ready&gt; &quot;</span><span class="p">);</span>
    <span class="k">switch</span> <span class="p">(</span><span class="n">CurTok</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">case</span> <span class="nl">tok_eof</span><span class="p">:</span>    <span class="k">return</span><span class="p">;</span>
    <span class="k">case</span> <span class="sc">&#39;;&#39;</span><span class="o">:</span>        <span class="n">getNextToken</span><span class="p">();</span> <span class="k">break</span><span class="p">;</span>  <span class="c1">// ignore top-level semicolons.</span>
    <span class="k">case</span> <span class="nl">tok_def</span><span class="p">:</span>    <span class="n">HandleDefinition</span><span class="p">();</span> <span class="k">break</span><span class="p">;</span>
    <span class="k">case</span> <span class="nl">tok_extern</span><span class="p">:</span> <span class="n">HandleExtern</span><span class="p">();</span> <span class="k">break</span><span class="p">;</span>
    <span class="k">default</span><span class="o">:</span>         <span class="n">HandleTopLevelExpression</span><span class="p">();</span> <span class="k">break</span><span class="p">;</span>
    <span class="p">}</span>
  <span class="p">}</span>
<span class="p">}</span>

<span class="c1">//===----------------------------------------------------------------------===//</span>
<span class="c1">// &quot;Library&quot; functions that can be &quot;extern&#39;d&quot; from user code.</span>
<span class="c1">//===----------------------------------------------------------------------===//</span>

<span class="c1">/// putchard - putchar that takes a double and returns 0.</span>
<span class="k">extern</span> <span class="s">&quot;C&quot;</span> 
<span class="kt">double</span> <span class="n">putchard</span><span class="p">(</span><span class="kt">double</span> <span class="n">X</span><span class="p">)</span> <span class="p">{</span>
  <span class="n">putchar</span><span class="p">((</span><span class="kt">char</span><span class="p">)</span><span class="n">X</span><span class="p">);</span>
  <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>

<span class="c1">//===----------------------------------------------------------------------===//</span>
<span class="c1">// Main driver code.</span>
<span class="c1">//===----------------------------------------------------------------------===//</span>

<span class="kt">int</span> <span class="n">main</span><span class="p">()</span> <span class="p">{</span>
  <span class="n">LLVMContext</span> <span class="o">&amp;</span><span class="n">Context</span> <span class="o">=</span> <span class="n">getGlobalContext</span><span class="p">();</span>

  <span class="c1">// Install standard binary operators.</span>
  <span class="c1">// 1 is lowest precedence.</span>
  <span class="n">BinopPrecedence</span><span class="p">[</span><span class="sc">&#39;&lt;&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">10</span><span class="p">;</span>
  <span class="n">BinopPrecedence</span><span class="p">[</span><span class="sc">&#39;+&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">20</span><span class="p">;</span>
  <span class="n">BinopPrecedence</span><span class="p">[</span><span class="sc">&#39;-&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">20</span><span class="p">;</span>
  <span class="n">BinopPrecedence</span><span class="p">[</span><span class="sc">&#39;*&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">40</span><span class="p">;</span>  <span class="c1">// highest.</span>

  <span class="c1">// Prime the first token.</span>
  <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&quot;ready&gt; &quot;</span><span class="p">);</span>
  <span class="n">getNextToken</span><span class="p">();</span>

  <span class="c1">// Make the module, which holds all the code.</span>
  <span class="n">TheModule</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Module</span><span class="p">(</span><span class="s">&quot;my cool jit&quot;</span><span class="p">,</span> <span class="n">Context</span><span class="p">);</span>

  <span class="c1">// Run the main &quot;interpreter loop&quot; now.</span>
  <span class="n">MainLoop</span><span class="p">();</span>

  <span class="c1">// Print out all of the generated code.</span>
  <span class="n">TheModule</span><span class="o">-&gt;</span><span class="n">dump</span><span class="p">();</span>

  <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p><a class="reference external" href="LangImpl4.html">Next: Adding JIT and Optimizer Support</a></p>
</div>
</div>


          </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="LangImpl4.html" title="4. Kaleidoscope: Adding JIT and Optimizer Support"
             >next</a> |</li>
        <li class="right" >
          <a href="LangImpl2.html" title="2. Kaleidoscope: Implementing a Parser and AST"
             >previous</a> |</li>
  <li><a href="http://llvm.org/">LLVM Home</a>&nbsp;|&nbsp;</li>
  <li><a href="../index.html">Documentation</a>&raquo;</li>

          <li class="nav-item nav-item-1"><a href="index.html" >LLVM Tutorial: Table of Contents</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer" role="contentinfo">
        &copy; Copyright 2003-2015, LLVM Project.
      Last updated on 2015-09-08.
      Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.3.1.
    </div>
  </body>
</html>